
using System;
using System.Collections.Generic;

using Grr;
using Grr.Web;
using Grr.Models;

using Castle.MonoRail.Framework;
using Castle.MonoRail.Framework.Views.Aspx;

public partial class Views_Grurrah_search : GrurrahViewPage {

    private static readonly int MaxResults = 10;
    private SearchResult result;

    protected override string TabName
    {
        get { return "search"; }
    }
    protected override void  SetProperties()
    {
        SearchTerm = PropertyBag["SearchTerm"] as string;
        SearchTermLabel.Text = SearchTerm;

        result = PropertyBag["SearchResult"] as SearchResult;
        if (result != null)
        {
            NextButton.Visible = result.MoreMatchesAvailable;
        }
    }

    public string SearchTerm
    {
        get
        {
            object o = ViewState["SearchTerm"];
            if (o == null)
                return String.Empty;
            return (string)o;
        }
        set
        {
            ViewState["SearchTerm"] = value;
        }
    }

    public int CurrentResultsIndex
    {
        get
        {
            object o = ViewState["CurrentResultsIndex"];
            if (o == null)
                return 0;
            return (int)o;
        }
        set
        {
            ViewState["CurrentResultsIndex"] = value;
        }
    }

    public SearchResult Result
    {
        get { return result; }
    }

    protected void NextButton_Click(object sender, EventArgs e)
    {
        result = Search.Query(SearchTerm, MaxResults, CurrentResultsIndex + MaxResults);
        CurrentResultsIndex += MaxResults;
        ResultsPanel.ForceAnUpdate();

        PrevButton.Visible = true;
        NextButton.Visible = result.MoreMatchesAvailable;
    }
    protected void PrevButton_Click(object sender, EventArgs e)
    {
        result = Search.Query(SearchTerm, MaxResults, CurrentResultsIndex - MaxResults);
        CurrentResultsIndex -= MaxResults;
        ResultsPanel.ForceAnUpdate();

        NextButton.Visible = true;
        PrevButton.Visible = CurrentResultsIndex != 0;
    }
    protected void SearchAgainButton_Click(object sender, EventArgs e)
    {
        string query = StringUtil.Clean (SearchAgainTextBox.Text);
        result = Search.Query(query, MaxResults, 0);
        CurrentResultsIndex = 0;
        ResultsPanel.ForceAnUpdate();

        NextButton.Visible = result.MoreMatchesAvailable;
        PrevButton.Visible = false;

        SearchTerm = query;
        SearchTermLabel.Text = SearchTerm;
    }
}
